let express = require('express');
let session = require('express-session');
let MongoStore = require('connect-mongo')(session);
let bodyParser = require('body-parser');
let User = require('./model');
let app = express();
var md5=require("md5")
app.use(session({
  secret: 'keyboard cat', //用来注册session id 到cookie中，相当与一个密钥
  resave: false, //每次是否重新保存
  saveUninitialized: true,//是否设置session在存储容器中可以给修改,
  store: new MongoStore({url: 'mongodb://localhost:27017/react'})
}));

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080'); //允许8080端口访问
    res.header('Access-Control-Allow-Headers', 'Content-Type,Accept'); //允许接收的头
    res.header('Access-Control-Allow-Method', 'GET,POST'); //允许的方法
    res.header('Access-Control-Allow-Credentials', 'true'); //允许跨域设置cookie
    if (req.method == 'OPTIONS') { //如果发的是options的请求，响应ok即可
      res.end(200); 
    } else {
      next();
    }
  });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.listen("3000",function(){
  console.log('Express server listening on port 3000');
})



//获取轮播图数据 当访问/slider的时候将数据返回
let sliders=require('./data/slider')
app.get('/slider',function(req,res){
    res.json(sliders)
})

let lessonList=require('./data/lessonList')
app.get('/lessonList/:type/:offset/:limit',function(req,res){ //参数是随机的，但是必须要有
  let {type,offset,limit}=req.params
  console.log(type,offset,limit)
  res.json(lessonList)
}) 

app.post('/api/reg',function(req,res){
  console.log(req.body.password)
  //加了密码
  req.body.password=md5(req.body.password)
  console.log(req.body)
  User.findOne({username:req.body.username}).then(doc=>{
    if(doc){
      res.json({err:'用户存在了'})
    }else{
      User.create(req.body).then(doc=>{
        req.session.user=doc; //将当前用户存到session中
        res.json(req.session.user)
      })
    }
  })
})

//验证用户是否登录
app.get('/api/auth',function(req,res){
  console.log(req.session);
  if(req.session.user){
    res.json(req.session.user);
  }else{
    res.json('未登录');
  }
})

//登录
app.get('/api/login',function(req,res){
  req.body.password=md5(req.body.password)
  User.findOne(req.body).then(data=>{
    if(data){
      req.session.user=data;
      res.json(req.session.user)
    }else{
      res.json({err:'校验你的用户名或密码'})
    }
  })
})